package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Answer;
import cn.tedu.knows.portal.service.IAnswerService;
import cn.tedu.knows.portal.vo.AnswerVo;
import com.sun.org.apache.bcel.internal.generic.IASTORE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-05-25
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {

    @Resource
    private IAnswerService answerService;

    @PostMapping("")
    //只有老师身份才能回答问题
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public Answer postAnswer(
            @AuthenticationPrincipal UserDetails user,
            @Validated AnswerVo answerVo,
            BindingResult result){
        log.debug("获得用户提交的信息:{}",answerVo);
        if(result.hasErrors()){
            String msg=result.getFieldError()
                    .getDefaultMessage();
            throw new ServiceException(msg);
        }
        //调用业务逻辑层方法!
        Answer answer=answerService.saveAnswer(
                answerVo,user.getUsername());
        return answer;
    }

    //根据问题id查询所有回答的控制器方法
    // /v1/answers/question/154
    @GetMapping("/question/{id}")
    public List<Answer> questionAnswers(
            @PathVariable Integer id){
        if(id == null){
            throw new ServiceException("问题id不能为空");
        }
        List<Answer> answers=answerService
                .getAnswersByQuestionId(id);
        return answers;
    }

    @GetMapping("/{answerId}/solved")
    public String solved(
            @PathVariable Integer answerId){
        boolean isAccept=answerService.accept(answerId);
        if(isAccept){
            return "ok";
        }else{
            //上面方法没有返回false的可能,这里只是逻辑判断
            return "???";
        }
    }







}
